import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, message } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import React, { PureComponent } from 'react';

import { PrimaryGhostC, FirstHeaderC, SecondHeaderC, PrimaryC, DATA_ENTRY, FormGroup, FixedButtonC } from '../../../comps';
import AssetPackage from '../outsourceInvestMsgMaintain/assetPackage';
import ValuateAnalysisInfo from '../valuationAnalysis/valuateAnalysisInfo';

@Form.create()
@connect(({ qualificationManagementPlanMaintenanceM, loading, userM: user }) => ({ qualificationManagementPlanMaintenanceM, loading, user }))
// operateType=1 新增, operateType=2 编辑 operateType=3 详情  operateType=4 估值解析
export default class updateModelC extends PureComponent {
  // eslint-disable-next-line react/static-property-placement
  static defaultProps = {
    onRef: () => {}, // 本组件的引用
    onBack: () => {}, // 组件返回上一级
    id: undefined, // 获取详情的id
    operateType: undefined, // operateType=1 新增, operateType=2 编辑 operateType=3 详情  operateType=4 估值解析
  };

  constructor(props) {
    super(props);
    this.state = {
      assetType: undefined,
      rateType: '', // 利率类型
      interestMethod: undefined, // 计息方式
      isHasYqRate: '',
      planCreateDate: undefined,
      planEndDate: undefined,
      ref: undefined,
      superviseStateInfoRef: null,
      baseInfoRef: null,
      assetPackageRef: null,
      data: {
        assetType: undefined,
        zjUseHy: 'J66',
        isHasYqRate: '0',
        managementRate: 0,
        trusteeshipRate: 0,
        transactionRelatedTotalRate: 0,
        intermediaryOrgTotalRate: 0,
        otherTotalRate: 0,
      },
      issuerList: [], // 管理人
    };
  }

  componentDidMount() {
    this.props.onRef(this);
    this.props.dispatch({
      type: 'qualificationManagementPlanMaintenanceM/getIssuerList',
      payload: {},
      callback: (data) => {
        if (data) {
          this.setState({
            issuerList: data,
          });
        } else {
          this.setState({
            issuerList: [],
          });
        }
      },
    });
    if (this.props.operateType == 2 || this.props.operateType == 3) {
      this.getDetail();
    }
  }

  getDetail = () => {
    this.props.dispatch({
      type: 'qualificationManagementPlanMaintenanceM/queryOne',
      payload: {
        id: this.props.id,
      },
      callback: (type, data) => {
        if (type == 'success') {
          this.setState({
            data,
            assetType: data.assetType,
            isHasYqRate: data.isHasYqRate,
            planCreateDate: data.planCreateDate,
            planEndDate: data.planEndDate,
            rateType: data.rateType,
            interestMethod: data.interestMethod,
          });
        }
      },
    });
  };

  // 返回主页面
  onBack = (type) => {
    this.props.onBack(type);
    // 重置form表单事件
    // this.props.form.resetFields()
  };

  // 取消点击事件
  onCancel = () => {
    this.onBack('cancel');
  };

  // 确认按钮点击事件
  onOk = () => {
    const { operateType, id } = this.props;
    if (operateType == 4) {
      this.props.dispatch({
        type: 'qualificationManagementPlanMaintenanceM/saveValuateAnalysis',
        payload: {
          id,
          ...this.state.ref.getInfo(),
        },
        callback: (type) => {
          if (type == 'success') {
            // message.success('保存成功')
            this.onBack('ok');
          }
        },
      });
    }
    if (operateType == 1 || operateType == 2) {
      const values1 = this.state.baseInfoRef.getFormGroupData();
      if (values1) {
        const assetPackageData = this.state.assetPackageRef?.getInfo();
        if (assetPackageData === null) return;

        this.props.dispatch({
          type: 'qualificationManagementPlanMaintenanceM/saveData',
          payload: {
            ...values1,
            planCreateDate: values1.planCreateDate ? moment(values1.planCreateDate).format('YYYY-MM-DD') : null,
            planEndDate: values1.planEndDate ? moment(values1.planEndDate).format('YYYY-MM-DD') : null,
            ...(operateType == 1 ? { type: 1 } : { type: 2, id }),
            fixedRate: values1.fixedRate != null && values1.fixedRate != undefined ? (values1.fixedRate * 100000) / 10000000 : null,
            files: assetPackageData,
            jgbb_fdyz: values1?.jgbb_fdyz || values1.jgbb_fdyz == 0 ? values1.jgbb_fdyz / 100 : null,
          },
          callback: (type) => {
            if (type == 'success') {
              message.success('保存成功');
              this.onBack('ok');
            }
          },
        });
      } else {
        return false;
      }
    }
  };

  // 用户基本信息
  baseInfo = () => {
    const { data, rateType, superviseStateInfoRef, interestMethod, planCreateDate, planEndDate } = this.state;
    const {
      qualificationManagementPlanMaintenanceM: { splitWayList, baseRate, interestMethodList },
      operateType,
    } = this.props;
    const disabled = operateType == 3;
    return (
      <>
        <SecondHeaderC title='基础信息' />
        <FormGroup
          dataSource={[
            {
              dataIndex: 'tradingcode',
              title: '证券代码',
              type: DATA_ENTRY.INPUT,
              initialValue: data.tradingcode,
              disabled: operateType == 2 ? true : disabled,
              showALLValue: true,
              max: 256,
              rules: [{ required: true, message: '请输入证券代码' }],
            },
            {
              dataIndex: 'tradingname',
              title: '证券全称',
              type: DATA_ENTRY.INPUT,
              initialValue: data.tradingname,
              disabled,
              max: 200,
              showALLValue: true,
              rules: [{ required: true, message: '请输入证券名称' }],
            },
            {
              dataIndex: 'secuabbr',
              title: '证券简称',
              type: DATA_ENTRY.INPUT,
              initialValue: data.secuabbr,
              disabled,
              rules: [{ required: true, message: '请输入证券简称' }],
            },
            {
              dataIndex: 'manager',
              title: '管理人名称',
              type: DATA_ENTRY.INPUT,
              initialValue: data.manager,
              disabled,
              max: 200,
              rules: [{ required: true, message: '请输入管理人' }],
            },
            {
              dataIndex: 'parTotalValue',
              title: '初始份额面值',
              type: DATA_ENTRY.INPUTNUMBER,
              initialValue: data.parTotalValue,
              min: 0,
              max: 999999999999.9999,
              disabled,
              precision: 4,
              unit: '元',
              rules: [{ required: true, message: '请输入初始份额面值' }],
            },
            {
              dataIndex: 'currency',
              title: '币种',
              type: DATA_ENTRY.INPUT,
              initialValue: data.currency || 'CNY',
              disabled: true,
              rules: [{ required: true, message: '请选择币种' }],
            },
            {
              dataIndex: 'planCreateDate',
              title: '成立日',
              type: DATA_ENTRY.SINGLEDATE,
              initialValue: data.planCreateDate ? moment(planCreateDate) : null,
              disableEnd: planEndDate ? moment(planEndDate).add(1, 'days') : undefined,
              disabled,
              onChange: (e) => {
                this.setState({ planCreateDate: e ? e.format('YYYY-MM-DD') : undefined });
              },
              rules: [{ required: true, message: '请选择成立日期' }],
            },
            {
              dataIndex: 'planEndDate',
              title: '到期日',
              type: DATA_ENTRY.SINGLEDATE,
              initialValue: data.planEndDate ? moment(data.planEndDate) : null,
              disableBegin: planCreateDate ? moment(planCreateDate).subtract(1, 'days') : undefined,
              disabled,
              onChange: (e) => {
                this.setState({ planEndDate: e ? e.format('YYYY-MM-DD') : undefined });
              },
              rules: [{ required: true, message: '请选择终止日期' }],
            },
            {
              dataIndex: 'assetType',
              title: '资产类别',
              positionBody: true,
              type: DATA_ENTRY.SELECT,
              dataSource: this.props.qualificationManagementPlanMaintenanceM?.assetTypeList || [],
              initialValue: data.assetType,
              allowClear: true,
              disabled,
              onChange: (e) => {
                superviseStateInfoRef?.props?.form.setFieldsValue({
                  isBankLczp: undefined,
                  isJrzcTzgs: undefined,
                });
                this.setState({ assetType: e });
              },
            },
            {
              dataIndex: 'planProperty',
              title: '资产属性',
              positionBody: true,
              type: DATA_ENTRY.SELECT,
              dataSource: this.props.qualificationManagementPlanMaintenanceM?.planPropertyList || [],
              initialValue: data.planProperty,
              allowClear: true,
              disabled,
            },
            {
              dataIndex: 'price',
              title: '发行规模',
              type: DATA_ENTRY.INPUTNUMBER,
              initialValue: data.price,
              unit: '元',
              splitStyle: true,
              precision: 2,
              max: 999999999999.99,
              disabled,
            },
            {
              dataIndex: 'splitWay',
              title: '拆分方式',
              type: DATA_ENTRY.SELECT,
              helper: '用于估值解析后的产品持仓分配',
              dataSource: splitWayList,
              initialValue: data.splitWay,
              disabled,
              allowClear: true,
              rules: [{ required: true, message: '请选择拆分方式!' }],
            },
            {
              dataIndex: 'rateType',
              title: '利率类型',
              type: DATA_ENTRY.SELECT,
              dataSource: [
                { value: '0', title: '固定' },
                { value: '1', title: '浮动' },
                { value: '2', title: '净值' },
              ],
              initialValue: data.rateType,
              disabled,
              rules: [{ required: true, message: '请选择利率类型!' }],
              onChange: (e) => {
                this.setState({ rateType: e, interestMethod: undefined });
              },
            },
            // 当选择附息式时，保持当前其他字段展示不变。当选择利随本清式时，利率和计息基础正常展示，计息频率不展示
            {
              dataIndex: 'interestMethod',
              title: '计息方式',
              type: DATA_ENTRY.SELECT,
              dataSource: interestMethodList,
              initialValue: data.interestMethod,
              disabled,
              hide: rateType != '0',
              rules: [{ required: true, message: '请选择计息方式!' }],
              onChange: (e) => {
                this.setState({ interestMethod: e });
              },
            },
            {
              dataIndex: 'fixedRate',
              title: '利率',
              type: DATA_ENTRY.INPUTNUMBER,
              unit: '%',
              splitStyle: true,
              max: 99.99999,
              precision: 5,
              initialValue: data.fixedRate != null ? data.fixedRate * 100 : null,
              disabled,
              hide: rateType != '0' || (interestMethod != 'lsbqs' && interestMethod != 'fxs'),
              rules: [{ required: true, message: '请选择利率类型!' }],
            },
            {
              dataIndex: 'interestBasis',
              title: '计息基础',
              type: DATA_ENTRY.SELECT,
              dataSource: this.props.qualificationManagementPlanMaintenanceM?.interestBasisList?.filter((x) => x.value != '5') || [],
              initialValue: data.interestBasis,
              disabled,
              hide: rateType != '0' || (interestMethod != 'lsbqs' && interestMethod != 'fxs'),
              rules: [{ required: true, message: '请选择基准利率!' }],
            },
            {
              dataIndex: 'interestRate',
              title: '计息频率',
              type: DATA_ENTRY.INPUTNUMBER,
              unit: '次',
              max: 10000,
              min: 1,
              precision: 0,
              initialValue: data.interestRate,
              disabled,
              hide: rateType != '0' || interestMethod != 'fxs',
              rules: [{ required: true, message: '请输入利率类型!' }],
            },
            {
              dataIndex: 'jgbb_jzllzl',
              title: '基准利率',
              type: DATA_ENTRY.SELECT,
              dataSource: baseRate,
              initialValue: data.jgbb_jzllzl,
              allowClear: true,
              disabled,
              hide: rateType != '1',
              rules: [{ required: true, message: '请输入基准利率!' }],
            },
            {
              dataIndex: 'jgbb_fdyz',
              title: '浮动因子',
              type: DATA_ENTRY.INPUTNUMBER,
              precision: 5,
              unit: 'bp',
              initialValue: data?.jgbb_fdyz || (data && data.jgbb_fdyz == 0) ? data?.jgbb_fdyz * 100 : null,
              disabled,
              hide: rateType != '1',
              rules: [{ required: true, message: '请选择浮动因子!' }],
            },
          ]}
          onRef={(ref) => {
            this.state.baseInfoRef = ref;
          }}
        />
      </>
    );
  };

  render() {
    const { operateType } = this.props;
    return (
      <FixedButtonC
        topHtml={
          <div>
            <FirstHeaderC title={`资产管理计划维护-${operateType == 3 ? '详情' : operateType == 1 ? '新增' : '编辑'}`} />
            {operateType != 4 && (
              <>
                <Row style={{ marginBottom: '10px' }}>
                  <Col>
                    {/* 基础信息 */}
                    {this.baseInfo()}
                  </Col>
                </Row>
                <AssetPackage
                  type={operateType} // 仅在type=3时（查看详情）做置灰处理
                  initialData={operateType == 1 ? undefined : this.state.data?.files ? this.state.data?.files : undefined}
                  onRef={(e) => this.setState({ assetPackageRef: e })}
                />
              </>
            )}
            {(operateType == 3 || operateType == 4) && (
              <Row style={{ marginBottom: '10px' }}>
                <Col>
                  {/* 估值解析 */}
                  <ValuateAnalysisInfo
                    id={this.props.id}
                    dimension='2'
                    type={2} // 1新增2详情
                    onRef={(e) => this.setState({ ref: e })}
                  />
                </Col>
              </Row>
            )}
          </div>
        }
        bottomHtml={
          <div style={{ display: 'flex', width: '100%', justifyContent: 'center' }}>
            <PrimaryGhostC style={{ margin: '0 10px' }} title='取消' onClick={this.onCancel} />
            {operateType != 3 && (
              <PrimaryC
                style={{ margin: '0 10px' }}
                title='确定'
                onClick={this.onOk}
                loading={
                  this.props.loading.effects['qualificationManagementPlanMaintenanceM/saveData'] == true ||
                  this.props.loading.effects['qualificationManagementPlanMaintenanceM/valuateAnalysis'] == true
                }
              />
            )}
          </div>
        }
      />
    );
  }
}
